// webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

const isProd = process.env.NODE_ENV === 'production';

module.exports = {
    mode: isProd ? 'production' : 'development',
    entry: path.resolve(__dirname, 'src/main.js'),
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'static/js/[name].[contenthash:8].js',
        chunkFilename: 'static/js/[name].[contenthash:8].chunk.js',
        publicPath: '/',   // 若挂子路径再改
    },
    devtool: isProd ? false : 'cheap-module-source-map',
    module: {
        rules: [
            {
                test: /\.m?js$/,
                exclude: /(node_modules|public)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: [['@babel/preset-env', { targets: 'defaults', modules: false }]]
                    }
                }
            },
            // 如果你以后在 JS 里 import CSS 再打开：
            // { test: /\.css$/, use: ['style-loader', 'css-loader'] }
        ]
    },
    plugins: [
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, 'index.html'),
            inject: 'body',
            scriptLoading: 'defer',
            minify: isProd ? { collapseWhitespace: true, removeComments: true } : false
        }),
        new CopyWebpackPlugin({
            patterns: [
                { from: 'public', to: 'public', noErrorOnMissing: true },
                { from: 'pages', to: 'pages', noErrorOnMissing: true }
            ]
        })
    ],
    devServer: {
        port: 8080,
        open: true,
        hot: true,
        historyApiFallback: true,  // 虽用 hash 路由，开着更稳
        static: [
            { directory: path.resolve(__dirname, 'public'), publicPath: '/public' },
            { directory: path.resolve(__dirname, 'pages'), publicPath: '/pages' }
        ]
    },
    optimization: {
        splitChunks: { chunks: 'all' },
        runtimeChunk: 'single'
    },
    performance: { hints: false }
};
